/**
 * 注解传入的roles参数外的权限守卫
 */

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { user } from '@prisma/client';
import { Observable } from 'rxjs';
import { Role } from '../enum';

@Injectable()
export class RoleGuard implements CanActivate {
  constructor(private reflector: Reflector) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    // 通过解析携带token的请求数据，解析是那个用户发起数据请求
    const user = context.switchToHttp().getRequest().user as user;
    // roles 为注解中@Auth(Role.ADMIN)传入的角色 没有传入就为空
    const roles = this.reflector.getAllAndMerge<Role[]>('roles', [
      context.getHandler(),
      context.getClass(),
    ]);
    // console.log(roles);
    return roles.length ? roles.some((role) => user.role == role) : true;
  }
}
